package com.baoyouqun.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baoyouqun.base.SystemConstant;
import com.baoyouqun.base.utils.ConvertUtils;
import com.baoyouqun.domain.CreateCmd.UserPointsCreateCmd;
import com.baoyouqun.domain.Query.UserPointsQuery;
import com.baoyouqun.domain.UpdateCmd.UserPointsUpdateCmd;
import com.baoyouqun.domain.VO.UserPhoneVO;
import com.baoyouqun.domain.VO.UserPointsVO;
import com.baoyouqun.domain.VO.UserVO;
import com.baoyouqun.entity.User;
import com.baoyouqun.entity.UserPoints;
import com.baoyouqun.mapper.UserPointsMapper;
import com.baoyouqun.service.UserPointsService;
import com.baoyouqun.service.UserService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@Service
public class UserPointsServiceImpl extends ServiceImpl<UserPointsMapper, UserPoints> implements UserPointsService {

    @Resource
    private UserPointsMapper userPointsMapper;
    @Resource
    private UserService userService;

    @Override
    public SingleResponse<UserPointsVO> create(UserPointsCreateCmd cmd) {
        UserPoints entity =
                ConvertUtils.copyBean(cmd, UserPoints.class);
        Boolean result = save(entity);
        if (!result) {
            return SingleResponse.buildFailure("100101", "创建失败");
        }

        UserPointsVO vo =
                ConvertUtils.copyBean(entity, UserPointsVO.class);
        return SingleResponse.of(vo);
    }

    @Override
    public Response update(UserPointsUpdateCmd cmd) {
        if (Objects.isNull(cmd)) {
            return Response.buildFailure("100301", "参数不能为空");
        }
        if (StringUtil.isBlank(cmd.getId())) {
            return Response.buildFailure("100302", "ID不能为空");
        }
        UserPoints oldEntity = getById(cmd.getId());
        if (Objects.isNull(oldEntity)) {
            return Response.buildFailure("100303", "未查询到此数据");
        }
        oldEntity = ConvertUtils.copyBean(cmd, UserPoints.class);
        Boolean result = updateById(oldEntity);
        if (result) {
            return Response.buildSuccess();
        } else {
            return Response.buildFailure("100304", "更新失败");
        }
    }

    @Override
    public UserPointsVO selectById(String id) {
        UserPoints entity = userPointsMapper.selectById(id);
        UserPointsVO vo =
                ConvertUtils.copyBean(entity, UserPointsVO.class);
        return vo;
    }

    @Override
    public IPage<UserPointsVO> pageVo(UserPointsQuery query) {
        IPage<UserPoints> page = new Page<UserPoints>(query.getCurrent(), query.getSize());
        page = page(page, new LambdaQueryWrapper<UserPoints>());
        Page<UserPointsVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        List<UserPointsVO> records = ConvertUtils.copyBeanList(page.getRecords(), UserPointsVO.class);
        voPage.setRecords(records);
        return voPage;
    }

    @Override
    public UserPointsVO getByUserId(String userId) {
        UserPoints entity = getOne(new LambdaQueryWrapper<UserPoints>()
                .eq(UserPoints::getUserId, userId)
                .last("limit 1"));
        return ConvertUtils.copyBean(entity, UserPointsVO.class);
    }


    @Override
    public List<UserPointsVO> listUsersByNameOrPhone(String keyword) {
        if (StrUtil.isBlank(keyword)) {
            return Collections.emptyList();
        }

        // 1. 查询基准用户列表（必须全部包含）
        List<UserVO> userList = userService.listByNameOrPhone(keyword);
        if (CollUtil.isEmpty(userList)) {
            return Collections.emptyList();
        }

        // 2. 初始化结果集（包含所有用户，设置基础信息和默认积分）
        List<UserPointsVO> resultList = userList.stream().map(user -> {
            UserPointsVO vo = new UserPointsVO();
            // 基础用户信息（必须保留，不被覆盖）
            vo.setUserId(user.getId());
            UserPhoneVO userSimpleVO = new UserPhoneVO();
            userSimpleVO.setName(user.getName());
            userSimpleVO.setCellphone(user.getCellphone());
            vo.setUserSimpleVO(userSimpleVO);
            // 积分默认值
            vo.setTotalPoints(0);
            vo.setCurrentPoints(0);
            vo.setFrozenPoints(0); // 补充冻结积分默认值，避免null
            return vo;
        }).collect(Collectors.toList());

        // 3. 批量查询有积分记录的用户
        List<String> userIds = userList.stream().map(UserVO::getId).collect(Collectors.toList());
        List<UserPointsVO> pointsList = listByUserIds(userIds);
        if (CollUtil.isEmpty(pointsList)) {
            return resultList; // 无积分记录，直接返回初始化结果
        }

        // 4. 构建积分记录Map（userId -> 积分VO）
        Map<String, UserPointsVO> pointsMap = pointsList.stream()
                .collect(Collectors.toMap(UserPointsVO::getUserId, v -> v));

        // 5. 遍历结果集，只更新积分相关字段（保留基础信息）
        resultList.forEach(vo -> {
            UserPointsVO pointsVO = pointsMap.get(vo.getUserId());
            if (pointsVO != null) {
                // 只更新积分相关字段，不碰用户基础信息
                vo.setId(pointsVO.getId());
                vo.setCurrentPoints(pointsVO.getCurrentPoints()); // 覆盖默认值
                vo.setTotalPoints(pointsVO.getTotalPoints());     // 覆盖默认值
                vo.setFrozenPoints(pointsVO.getFrozenPoints());   // 覆盖默认值
                vo.setUpdateTime(pointsVO.getUpdateTime());
                vo.setCreateTime(pointsVO.getCreateTime());
                // 其他积分相关字段按需添加
            }
        });

        takeUserVO(resultList);
        return resultList;
    }

    private List<UserPointsVO> listByUserIds(List<String> userIds) {
        if (CollUtil.isEmpty(userIds)) {
            return Collections.emptyList();
        }
        List<UserPoints> list = list(new LambdaQueryWrapper<UserPoints>()
                .in(UserPoints::getUserId, userIds));
        return ConvertUtils.copyBeanList(list, UserPointsVO.class);
    }


    public void takeUserVO(List<UserPointsVO> list) {
        if (CollUtil.isEmpty(list)) {
            return;
        }
        List<String> userIds = list.stream()
                .map(UserPointsVO::getUserId)
                .filter(StringUtils::isNotBlank)  // 过滤空字符串
                .collect(Collectors.toList());

        if (CollUtil.isEmpty(userIds)) {
            return;
        }
        List<User> userList = userService.listByIds(userIds);  // 假设User的id字段也是String类型
        Map<String, User> userMap = userList.stream()
                .collect(Collectors.toMap(
                        User::getId,  // 以用户ID作为key（String类型）
                        user -> user,
                        (existing, replacement) -> existing  // 若有重复ID，保留第一个
                ));

        list.forEach(UserPointsVO -> {
            String userId = UserPointsVO.getUserId();
            User matchedUser = StringUtils.isNotBlank(userId) ? userMap.get(userId) : null;
            UserPhoneVO userPhoneVO = new UserPhoneVO();
            if (matchedUser != null) {
                userPhoneVO.setName(matchedUser.getName());  // 用户名/昵称
                userPhoneVO.setCellphone(matchedUser.getCellphone());  // 用户cell
            } else {
                // 未匹配到用户，设置默认值
                userPhoneVO.setName(SystemConstant.DEFAULT_NAME);
                userPhoneVO.setCellphone(SystemConstant.DEFAULT_HEAD_IMG);
            }
            UserPointsVO.setUserSimpleVO(userPhoneVO);  // 未匹配到用户时不显示手机号
        });
    }

}